package middleware

import (
	"fmt"
	"runtime/debug"
)

func ErrorHandlerWrap(handler func(context Context, err error, detail interface{})) Handler {
	return func(context Context, next Next) error {
		defer func() {
			if err := recover(); err != nil {
				debug.PrintStack()
				a := debug.Stack()
				handler(context, fmt.Errorf("%s", err), string(a))
			}
		}()
		err := next(nil)
		if err != nil {
			handler(context, err, nil)
		} else {
			result := context.GetResponse()
			err, ok := result.(error)
			if ok {
				handler(context, err, nil)
			}
		}

		return nil
	}
}
